<?php
/**
 * Created by MY_MIND.
 * User: WDJ
 * Date: 2018/7/4 0004
 * Time: 16:00
 */
namespace app\index\controller;

use \think\Controller;
use \think\Request;
use \think\Config;
use \think\Db;

/**
 *微信H5支付
 */
class Wechat extends Controller
{
    /**
     *  初始化数据
     */
    public $request;
    public $config;

    public function __construct()
    {
        parent::__construct();

        $this->config     =   Config::get('wxpay');
        $this->request    =   Request::instance();
        //读取微信支付的配置文件
    }

    /**
     * 发出h5支付请求
     * uid      游戏玩家ID
     * package  套餐ID
     */
    /**public function webPay()
    {
        //判断请求方式
        if($this->request->isAjax()){
            $post       =   $this->request->post();
            //查看购买金额
            $coin       =   Db::name('price')->where(['id' => $post['package']])->find();
            if(!$coin){
                exit(json_encode(['code' => 300 , 'result' => '无效套餐']));
            }

            $userInfo   =   getSqlConnec('QPAccountsDB_CHUI' , 'AccountsInfo')->where(['UserID' => $post['uid']])->find();
            if(!$userInfo){
//                exit(json_encode(['code' => 900 , 'result' => '游戏玩家不存在']));
            }

            $level      =   $userInfo['VIPLevel'] ? $userInfo['VIPLevel'] : 0;
            $discount   =   getSqlConnec('QPTreasureDB_CHUI' , 'VIPConfig')->where(['VIPLevel' => $level])->find()['DisCount'];
            $order_sn   =   'QA' . time() . createNoncestr(6);

             * 必传参数
             * appid    公众账号ID  mch_id  商户号 nonce_str   随机字符串   sign    签名
             * body     商品描述    out_trade_no    商户订单号   total_fee   总金额
             * spbill_create_ip 终端IP    notify_url  通知地址(不能带参数)
             * trade_type   交易类型(MWEB)  scene_info  场景信息(三种)
             * 1，IOS移动应用                                    2，安卓移动应用                                3，WAP网站应用
             * {"h5_info": //h5支付固定传"h5_info"          {"h5_info": //h5支付固定传"h5_info"               {"h5_info": //h5支付固定传"h5_info"
             * {"type": "IOS",  //场景类型                     {"type": "Android",  //场景类型                          {"type": "WAP",  //场景类型
             * "app_name": "",  //应用名                   "app_name": "",  //应用名                          "wap_url": "",//WAP网站URL地址
             * "bundle_id": ""  //bundle_id               "package_name": ""  //包名                         "wap_name": ""  //WAP 网站名
             * }                                          }                                                 }
             * }                                          }                                                }

            //判断客户端类型
            $client_type                =   Session::get('client_info.type');
            if($client_type == 'IOS'){
                $h5_info_str            =   '{"h5_info": {"type":"IOS","app_name": "' . Config::get($client_type)['app_name'] . '","bundle_id": "' . Config::get($client_type)['bundle_id'] . '"}}';
                $device_type            =   1;
            }elseif($client_type == 'Android'){
                $h5_info_str            =   '{"h5_info": {"type":"Androiod","app_name": "' . Config::get($client_type)['app_name'] . '","package_name": "' . Config::get($client_type)['package_name'] . '"}}';
                $device_type            =   2;
            }else{
                $h5_info_str            =   '{"h5_info": {"type":"WAP","wap_url": "' . $this->request->domain() . $this->request->url(). '","wap_name": "' . '吹牛游戏商城' . '"}}';
                $device_type            =   3;
            }

            $data['appid']              =   $this->config['appid'];
            $data['mch_id']             =   $this->config['mch_id'];
            $data['nonce_str']          =   createNoncestr();
            $data['body']               =   '吹牛游戏商城';
            $data['out_trade_no']       =   $order_sn;
            $data['total_fee']          =   1;//intval(ceil($discount * $coin['price']) * 100);
            $data['spbill_create_ip']   =   $this->request->ip();
            $data['notify_url']         =   'https://chuiniu.qiligame.com' . url('index/Wechat/getWxpayRes'); //$this->request->domain()
            $data['trade_type']         =   'MWEB';
            $data['scene_info']         =   '{"h5_info": {"type":"WAP","wap_url": "' . $this->request->domain() . $this->request->url(). '","wap_name": "' . '吹牛游戏商城' . '"}}';
            $data['sign']               =   $this->getSign($data);
            //接口地址
            $url                        =   'https://api.mch.weixin.qq.com/pay/unifiedorder';
            //发出请求
            list($flag, $result)        =   curlQuery($url, 'POST', arrayToXml($data), true, ['CERT_PEM' => $this->config['cert_pem'] , 'KEY_PEM' => $this->config['key_pem']]);
            if(!$flag){
                exit(json_encode(['code' => 500 , 'result' => '请求错误']));
            }
            $response_result            =   xmlToArray($result);
//            dump($response_result['return_code']);exit;
            //如果微信返回结果没有错的话直接接跳转到唤起微信支付的页面
            if($response_result['return_code'] == 'SUCCESS' && $response_result['result_code'] == 'SUCCESS'){
                //请求成功后添加支付记录
                $pay['uid']             =   $post['uid'];
                $pay['appid']           =   $data['appid'];
                $pay['mch_id']          =   $data['mch_id'];
                $pay['ip_address']      =   $data['spbill_create_ip'];
                $pay['device_type']     =   $device_type;
                $pay['order_sn']        =   $order_sn;
                $pay['sign']            =   $data['sign'];
                $pay['total_nums']      =   $coin['num'];
                $pay['total_fee']       =   $data['total_fee'];
                $pay['status']          =   0;
                $pay['create_time']     =   time();

                $recordPayLog           =   Db::name('pay_log')->insert($pay);
                if($recordPayLog !== false){
                    //保存成功后跳转唤起的URL
                    exit(json_encode(['code' => 0, 'result' => $response_result['mweb_url']]));
                }
            }elseif($response_result['result_code'] == 'FAIL'){
                exit(json_encode(['code' => $response_result['err_code'], 'result' => $response_result['err_code_des']]));
            }

        }
    }*/

    /**
     * 异步回调
     */
    public function getWxpayRes()
    {
        file_put_contents('clientpay.txt', file_get_contents('php://input'));
        $xml_data       =  xmlToArray(file_get_contents("php://input"));
        /**
         * 校验签名正确性，支付金额的正确性
         * 从记录表中找出订单号和签名都存在的说明是正确的来源数据
         */
        $result         =   Db::name('pay_log')->where(['order_sn' => $xml_data['out_trade_no']])->find();
        if($result){
            //更新游戏玩家UID的资产信息
            getSqlConnec('QPTreasureDB_CHUI' , 'GameScoreInfo')->where(['UserID' => $result['uid']])->setInc("Score" , $result['total_nums']);

            //更新支付记录的内容
            $update_pay     =   Db::name('pay_log')->where(['id' => $result['id']])->update(['status' => 1, 'update_time' => time(), 'transaction_id' => $xml_data['transaction_id']]);

            //更新订单记录信息
            $update_log     =   Db::name('shop_log')->where(['order_sn' => $result['order_sn'], 'type' => 1, 'uid' => $result['uid']])->update(['is_pay' => 1, 'pay_time' => time()]);

            if($update_pay !== false && $update_log !== false){
                $response_url    =   $this->request->domain() . $this->request->url();
                curlQuery($response_url, 'POST', arrayToXml(['return_code' => 'SUCCESS', 'msg' => 'OK']));
            }
        }
    }

    /**
     * 	作用：生成签名
     */
    public function getSign($Obj)
    {
        foreach ($Obj as $k => $v)
        {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);

        //签名步骤二：在string后加入KEY
        $String = $String."&key=" . $this->config['apikey'];

        //签名步骤三：MD5加密
        $String = md5($String);

        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);

        return $result_;
    }

    /**
     * 	作用：格式化参数，签名过程需要使用
     */
    private function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
    
}